#pragma once
#include <pthread.h>

class mutex
{
public:
    mutex()
    {
        pthread_mutex_init(&_mutex, nullptr);
    }

    int lock()
    {
        return pthread_mutex_lock(&_mutex);
    }

    int unlock()
    {
        return pthread_mutex_unlock(&_mutex);
    }

    ~mutex()
    {
        pthread_mutex_destroy(&_mutex);
    }

private:
    pthread_mutex_t _mutex;
};



//采用RAII风格, 实现智能互斥锁
//原理: 因为lock_guard对象是一个临时对象, 进作用范围调用构造函数实现上锁, 出作用范围调用析构函数实现解锁
class lock_guard
{
public:
    lock_guard(mutex& m)
        :_m(m)
    {
        _m.lock();
        //_pM->lock();
    }

    ~lock_guard()
    {
        _m.unlock();
        //_pM->unlock();
    }

private:
    mutex& _m;////外部锁的一个引用, 用指针也行
    //mutex* _pM;
};    
